package gy.com.sansharescuesystem.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import gy.com.sansharescuesystem.R;
import gy.com.sansharescuesystem.base.BaseActivity;
import gy.com.sansharescuesystem.callback.LoginCallBack;
import gy.com.sansharescuesystem.entity.LoginBean;
import gy.com.sansharescuesystem.modle.LoginModel;
import gy.com.sansharescuesystem.modle.impl.LoginModelImpl;
import gy.com.sansharescuesystem.utils.DialogUtils;
import gy.com.sansharescuesystem.utils.NetWorkUtils;
import gy.com.sansharescuesystem.utils.SharePreferenceUtils;
import gy.com.sansharescuesystem.utils.UIUtils;

/**
 * function:登录
 * author:zsf
 * time:2017.07.14
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener, View.OnFocusChangeListener {
    private Button loginBtn;
    private EditText loginEdt;
    private EditText passwordEdt;
    private ImageView rememberImgView;
    private TextView versionTw;
    private LinearLayout loginView;
    //登录成功，跳转页面，失败弹提示框
    //flagPwd = 0记住密码状态，flagPwd=1为取消记住状态。默认为记住密码状态
    private int flagPwd = 0;
    private static final int ACCESS_SUCCESS = 0;
    private static final int ACCESS_ERROR = 1;
    private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 2;
    private boolean firstStart = true;
    private Dialog waitDialog;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ACCESS_SUCCESS:
//                    loginBar.setVisibility(View.GONE);
                    DialogUtils.closeDialog(waitDialog);
                    loginBtn.setClickable(true);
                    LoginBean loginBean = (LoginBean) msg.obj;
                    if (loginBean.getFlag().equals("1") || loginBean.getFlag().equals("2")) {
////                             flag=1表示登录成功，flag=2表示已登录
                        SharePreferenceUtils.setStringSave(LoginActivity.this, "username", loginEdt.getText().toString());
                        if (flagPwd == 0) {
                            //flagPwd =0记住密码
                            SharePreferenceUtils.setStringSave(LoginActivity.this, "loginName", loginEdt.getText().toString());
                            SharePreferenceUtils.setStringSave(LoginActivity.this, "password", passwordEdt.getText().toString());
                            SharePreferenceUtils.setStringSave(LoginActivity.this, "flag", flagPwd + "");
                        } else if (flagPwd == 1) {
                            SharePreferenceUtils.setStringSave(LoginActivity.this, "loginName", "");
                            SharePreferenceUtils.setStringSave(LoginActivity.this, "password", "");
                        }
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    } else if (loginBean.getFlag().equals("0")) {
                        // flag=0表示登录失败
                        UIUtils.showToast(getApplicationContext(), "登录失败，请确认账号和密码是否正确！");
                    }
                    break;

                case ACCESS_ERROR:
                    DialogUtils.closeDialog(waitDialog);
                    loginBtn.setClickable(true);
                    UIUtils.showToast(getApplicationContext(), "登录异常，请稍后重试！");
                    break;

                default:

                    break;


            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getPermissions();
        initView();
        setWidgetListener();
        ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);

    }

    private void getPermissions() {
        if (VERSION.SDK_INT >= VERSION_CODES.M) {//如果API level 是大于等于 23(Android 6.0) 时
            //判断是否具有权限
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要向用户解释为什么需要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {

                }
                //请求权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_ACCESS_COARSE_LOCATION);
            }
        }
    }

    @Override
    protected void initView() {
        loginView = (LinearLayout) findViewById(R.id.longin_view);
        loginBtn = (Button) findViewById(R.id.loginBtn);

        loginEdt = (EditText) findViewById(R.id.loginEdt);
        passwordEdt = (EditText) findViewById(R.id.passwordEdt);
        rememberImgView = (ImageView) findViewById(R.id.remberPwdImgVw);
        versionTw = (TextView) findViewById(R.id.versionTw);
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            versionTw.setText("版本号： " + version);
        } catch (Exception e) {
            Log.e("exception", e.toString());
        }
        Intent intent = getIntent();
        String modifyPwdFlag = intent.getStringExtra("modify");
        if (modifyPwdFlag != null && modifyPwdFlag.equals("success")) {
            //修改密码成功，返回登录页
            loginEdt.setText(SharePreferenceUtils.getStringPerferences(this, "username", ""));
            passwordEdt.setText("");
            loginEdt.clearFocus();
            passwordEdt.setFocusable(true);
            passwordEdt.setFocusableInTouchMode(true);
            passwordEdt.requestFocus();
        } else {
            if (SharePreferenceUtils.getStringPerferences(this, "flag", "").equals("0")) {
                loginEdt.setText(SharePreferenceUtils.getStringPerferences(this, "loginName", ""));
                passwordEdt.setText(SharePreferenceUtils.getStringPerferences(this, "password", ""));
                loginEdt.clearFocus();
                passwordEdt.setFocusable(true);
                passwordEdt.setFocusableInTouchMode(true);
                passwordEdt.requestFocus();
                String content = passwordEdt.getText().toString();
                passwordEdt.setSelection(content.length());

            }
        }


    }

    @Override
    protected void setWidgetListener() {
        loginBtn.setOnClickListener(this);
        loginEdt.setOnFocusChangeListener(this);
        passwordEdt.setOnFocusChangeListener(this);
        rememberImgView.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginBtn:
                if (loginEdt.getText().toString().equals("")) {
                    UIUtils.showToast(getApplicationContext(), "用户名不能为空！");
                    return;
                }
                if (passwordEdt.getText().toString().equals("")) {
                    UIUtils.showToast(getApplicationContext(), "密码不能为空！");
                    return;
                }
                if (NetWorkUtils.IsHaveInternet(this)) {
                    login();
                } else {
                    UIUtils.showToast(this, "请确认是否有网络！");
                }

                break;


            case R.id.remberPwdImgVw:
                if (flagPwd == 0) {
                    rememberImgView.setImageResource(R.drawable.code);
                    flagPwd = 1;
                } else {

                    rememberImgView.setImageResource(R.drawable.code_rem);
                    flagPwd = 0;
                }
                break;
            default:
                break;
        }


    }

    private void login() {
        waitDialog= DialogUtils.createLoadingDialog(this,"登录中...",false);
        loginBtn.setClickable(false);
        Map<String, String> map = new HashMap<String, String>();
        map.put("loginName", loginEdt.getText().toString());
        map.put("password", passwordEdt.getText().toString());
        LoginModel loginModel = new LoginModelImpl();
        loginModel.getData(new LoginCallBack() {
            @Override
            public void onSuccse(LoginBean loginBean) {
                Message message = handler.obtainMessage();
                message.what = ACCESS_SUCCESS;
                message.obj = loginBean;
                handler.sendMessage(message);


            }

            @Override
            public void onFailed() {
                Message message = handler.obtainMessage();
                message.what = ACCESS_ERROR;
                handler.sendMessage(message);
            }
        }, map);


    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.loginEdt:
                if (hasFocus) {
                    if (!loginEdt.getText().toString().equals("")) {
                        String content = loginEdt.getText().toString();
                        loginEdt.setSelection(content.length());
                    }
              /*  else {
                    //打开本页面时，不隐藏hint,再次点击时，隐藏hint
                    if (!firstStart){
                        String hintText=loginEdt.getHint().toString();
                        loginEdt.setTag(hintText);
                        loginEdt.setHint("");
                    }

                    firstStart=false;
                }*/
                    passwordEdt.clearFocus();
                    loginEdt.setFocusable(true);
                    loginEdt.setFocusableInTouchMode(true);
                    loginEdt.requestFocus();
                }
                break;
            case R.id.passwordEdt:

                if (hasFocus) {

                    if (!passwordEdt.getText().toString().equals("")) {
                        String content = passwordEdt.getText().toString();
                        passwordEdt.setSelection(content.length());
                    }
              /*  else {
                    String hintText=passwordEdt.getHint().toString();
                    passwordEdt.setTag(hintText);
                    passwordEdt.setHint("");
                }*/
                    loginEdt.clearFocus();
                    passwordEdt.setFocusable(true);
                    passwordEdt.setFocusableInTouchMode(true);
                    passwordEdt.requestFocus();
                }

                break;

            default:


                break;


        }

    }

}
